package org.game.module.event.handler;

import java.util.List;
import java.util.Map;

import org.cfg.TaskCfg;
import org.cfg.cache.TaskCfgCache;
import org.constant.TaskConstant;
import org.game.db.bean.Player;
import org.game.db.bean.Task;
import org.game.db.cache.TaskCache;
import org.game.manager.TaskManager;
import org.game.msgBuilder.TaskMsgBuilder;
import org.game.plugin.event.GameEvent;
import org.game.plugin.event.GameEventHandler;
import org.game.plugin.event.GameEventListener;
import org.game.plugin.event.GameEventVector;
import org.game.protobuf.s2c.S2CShareMsg.ChangeType;
import org.game.protobuf.s2c.S2CTaskMsg.TaskInfo;

import com.google.common.collect.Lists;
/**
 * 任务完成事件处理器
 * @author win7
 *
 */
public class TaskFinishEventHandler implements GameEventHandler {

	/**
	 * 任务完成事件处理流程：
	 * 	1.遍历玩家所有任务Running状态的任务
	 * 	2.获取任务cfg
	 * 	2.根据入参校验和配置校验任务是否完成
	 */
	@Override
	public void onEvent(GameEventListener listener, GameEvent event) {
		Player player = event.getPlayer();
		// 取得玩家还在进行中的任务
		List<Task> runingTasks = TaskCache.me().getByPlayerId(player.getId());
//		List<Task> runingTasks = TaskCache.me().getByPlayerIdStatus(player.getId(), TaskConstant.STATUS_RUNING);
		for (Task task : runingTasks) {
			// 因为有了进度继承所以没有完成的活动和可以领奖的活动都要检查
			if (task.getStatus() == TaskConstant.STATUS_RECEIVE || task.getStatus() == TaskConstant.STATUS_TIME_OUT) {
				continue;
			}
			TaskCfg taskCfg = TaskCfgCache.me().getById(task.getCid());
			if (taskCfg == null){
				continue;
			}
			//完成任务：用的是完成任务的条件参数
			Map params = taskCfg.getFinishParams();
			handler(listener, event, new TaskVector(task),taskCfg.getFinishCondId(), params,taskCfg.getProgress());
		}
	}
	
	
	// 任务载体
	public static class TaskVector implements GameEventVector{
		private Task task;
		
		public TaskVector(Task task) {
			super();
			this.task = task;
		}

		@Override
		public int getProgress() {
			return task.getProgress();
		}

		@Override
		public void setProgress(int progress) {
			task.setProgress(progress);
		}

		@Override
		public void trigger(int maxProcess) {
			if (task.getProgress() >= maxProcess && task.getStatus() != TaskConstant.STATUS_FINISH) {
				task.setStatus(TaskConstant.STATUS_FINISH);
			}
			task.update();
		}

		@Override
		public void notify(Player player) {
			List<TaskInfo> taskInfos = Lists.newArrayList();
			taskInfos.add(TaskMsgBuilder.createTaskInfo(player, ChangeType.UPDATE, task));
			TaskManager.me().notifyTaskInfos(player, taskInfos);
		}
		
	}
}
